package com.chaos.auth.service.userdetails;

import cn.hutool.core.util.ObjectUtil;
import com.chaos.auth.api.data.RbacUserData;
import com.chaos.auth.api.dto.userdetails.AdminUserDetails;
import com.chaos.auth.service.RbacUserRoleService;
import com.chaos.auth.service.RbacUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Slf4j
@Component("adminDetailsService")
public class AdminDetailsService {
    @Resource
    private RbacUserService rbacUserService;

    @Resource
    private RbacUserRoleService rbacUserRoleService;


    public RbacUserData getRbacUserDataByPhone(String phone, Long tenantId) {
        RbacUserData query = RbacUserData.builder().mobile(phone).build();
        query.setTenantId(tenantId);
        return getRbacUserData(query);
    }

    public RbacUserData getRbacUserDataByUsername(String username, Long tenantId) {
        RbacUserData query = RbacUserData.builder().username(username).build();
        query.setTenantId(tenantId);
        return getRbacUserData(query);
    }

    public RbacUserData getRbacUserDataByUsername(String username) {
        return getRbacUserData(RbacUserData.builder().username(username).build());
    }

    private RbacUserData getRbacUserData(RbacUserData queryData) {
        List<RbacUserData> rbacUserDatas = rbacUserService.selectByData(queryData);
        if (ObjectUtil.isEmpty(rbacUserDatas)) {
            throw new DisabledException("用户不存在");
        }
        if (rbacUserDatas.size() > 1) {
            throw new DisabledException("用户名异常");
        }
        return rbacUserDatas.get(0);
    }

    public AdminUserDetails getAdminUserDetails(RbacUserData rbacUser) {
        Set<Long> roles = rbacUserRoleService.selectRolesByUserId(rbacUser.getId());
        if (ObjectUtil.isEmpty(roles)) {
            throw new DisabledException("该账户无有效权限!");
        }
        AdminUserDetails userDetails = new AdminUserDetails(rbacUser, roles);
        if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }

        return userDetails;

    }


}
